﻿public class Solution56
{

    public int[] MergeNew(int[] preArr, int[] curArr)
    {

        int curArrLength = curArr.Length;

        int startIndex = preArr[0];
        int endIndex = curArr[curArrLength - 1];

        int newarrLen = endIndex - startIndex + 1;
        int[] newarr = new int[newarrLen];

        int index = 0;
        for (int curNum = startIndex; curNum < endIndex; curNum++)
        {
            newarr[index] = curNum;
            index++;
        }

        return newarr;
    }

    public int[][] Merge(int[][] intervals)
    {

        //尾巴大于等于head，就说明重叠
        int arrNum = intervals.Length;
        int curarrLength = 0;
        int movearrLength = 0;
        Console.WriteLine("Merged Intervals:", arrNum);
        for (int i = 0; i < arrNum; i++)
        {
            curarrLength = intervals[i].Length;
            for (int j = i; j < arrNum; j++)
            {
                movearrLength = intervals[j].Length;
                Console.WriteLine("Merged Intervals:", intervals[i]);


                if (intervals[i][curarrLength - 1] >= intervals[j][0])
                {
                    //合并
                    int[] newarr = MergeNew(intervals[i], intervals[j]);


                    intervals[i] = newarr;
                    intervals[j] = newarr;

                }
                if (intervals[i][0] <= intervals[j][movearrLength - 1])
                {
                    //合并
                    int[] newarr = MergeNew(intervals[j], intervals[i]);

                    intervals[i] = newarr;
                    intervals[j] = newarr;
                }


            }



        }




        return intervals;
    }
}


class Program56
{
    public static void Main56(string[] args)
    {
        int[][] intervals = new int[][] {
            new int[]{2, 8},
            new int[] {2, 6},
            new int[] {8, 10},
            new int[] {15, 18}
        };
        foreach (int[] interval in intervals)
        {
            Console.WriteLine($"[{interval[0]}, {interval[1]}]");
        }
        Solution56 solution = new Solution56();
        int[][] mergedIntervals = solution.Merge(intervals);

        Console.WriteLine("Merged Intervals:");
        foreach (int[] interval in mergedIntervals)
        {
            Console.WriteLine($"[{interval[0]}, {interval[1]}]");
        }
    }


}